package com.yunkaweilai.android.fragment.shop;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.shop.PtShopActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.shop.ShopModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 商品列表
 * Created by Administrator on 2017/6/13.
 */

public class CommodityInfoFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    @BindView(R.id.id_listView)
    ListView idListView;
    Unbinder unbinder;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    private String goods_category_id = "";
    private ArrayList<ShopModel.DataBean.ListBean> shoplist = new ArrayList<>();
    private CommonAdapter<ShopModel.DataBean.ListBean> adapter;
    private int mpage = 1;
    private boolean mHasMore = true;
    private AppRuleModel.DataBean.InfoBean appRuleModel;

    public static CommodityInfoFragment getInstentce(String goods_category_id) {
        CommodityInfoFragment fragment = new CommodityInfoFragment();
        fragment.goods_category_id = goods_category_id;
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_list;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView,this,true);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        appRuleModel = BaseApplication.getAppRuleModel();
        initAdapter();
        initClick();
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp(true);
            }
        });
        initHttp(true);
    }

    private void initClick() {
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("20")){
                    PtShopActivity.actionStart(mAc, shoplist.get(position).getId() + "");
                }
            }
        });

    }

    private boolean initHttp(final boolean refresh) {
        mpage = refresh?1:mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.SHOP_INFO_LIST)
                .addParams("ShowPage","1")
                .addParams("PageSize","10")
                .addParams("is_show_status","0")
                .addParams("CurrPage",mpage+"")
                .addParams("goods_category_id", goods_category_id).log(TAG)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            ShopModel shopModel = gson.fromJson(json, ShopModel.class);
                            if (refresh) {
                                shoplist.clear();
                            }

                            if (shopModel.getData().getList()!= null && shopModel.getData().getList().size() != 0) {
                                shoplist.addAll(shopModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = shopModel.getData().getPage().isNext();//如果接收到完整10个数据，说明还有下一页
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh){
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null){
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null){
                contentView.endLoadingMore();
            }
        }
    }

    private void initAdapter() {
        adapter = new CommonAdapter<ShopModel.DataBean.ListBean>(getActivity(), R.layout.item_list_shop_info, shoplist) {
            @Override
            protected void convert(ViewHolder viewHolder, ShopModel.DataBean.ListBean item, int position) {
                viewHolder.setVisible(R.id.id_tv_tingyong,false);
                TextView tvname = viewHolder.getView(R.id.id_tv_name);
                if (item.getStatus().equals("0")){
//                    viewHolder.setVisible(R.id.id_tv_tingyong,true);
                    tvname.setText(Html.fromHtml(item.getGoods_name() +"    "+ "<font color='#F53435'>" + "停用中" + "</font>" ));
                }else {
                    tvname.setText(item.getGoods_name() + "");
                }
                viewHolder.setVisible(R.id.id_tv_duo,false);
                if (item.getSkuList().size() > 1){
                    viewHolder.setVisible(R.id.id_tv_duo,true);
                }
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc,item.getGoods_image(),mIdImg);

                viewHolder.setText(R.id.id_tv_price, item.getShow_shop_price() + "/" + item.getUnit());
                viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGoods_sku() + " 库存：" + item.getMay_use_stock());
            }
        };
        idListView.setAdapter(adapter);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
